<?php

namespace app\award;

use app\models\NewLevel;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\ProductArea;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;

class AwardOld
{
    protected $order;
    protected $user;

    protected $set;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $this->set = SetUserUp::getLastOne();

        $is_bao = ProductArea::checkBao($product_id);
        $is_repeat = ProductArea::checkRepeat($product_id);

        $is_new1 = ProductArea::checkNew1($product_id);
        $is_new2 = ProductArea::checkNew2($product_id);

        // 新报单
        if ($is_new1) {

            $this->newRecommend();

            // 上单 450
            // $this->new450();

            // $this->newProfit();
        }

        // 新复购
        if ($is_new2) {
            // $this->newProfit();

            $this->new_repeat_diff();
        }

        if ($is_bao) {

            $this->recommend();

            // $this->team();
            $this->newTeam();
            $this->profit();

            $this->add_award();
        }

        if ($is_repeat) {

            $this->diff();

            // $this->team();
            $this->newTeam();
            $this->profit();

            $this->add_award();
        }
    }

    // 团队下级上单2999奖励450
    private function new450()
    {
        // 找关系链上的VIP3, VIP4, 找第1个,
        // 如果第1个是VIP3, 则有,
        // 如果第1个是VIP4, 则不合理(第1个,如果是直推, 则有1650 + 450)

        $chain = Chain::getReferrerChainNew($this->order->user_id, [NewLevel::$keys['vip4'], NewLevel::$keys['vip3']], true);

        if ($chain) {
            $chain = $chain[0];

            if ($chain->new_level == NewLevel::$keys['vip3']) {

                $commission = 450;
                $this->saveCommission($chain->id, $this->order->user_id, $this->order->id, $commission, '203', '上单');

                // 平级直推事业部5%业绩奖励
                $amount = $this->order->total_pay - $this->order->total_freight;
                $r = Chain::getReferrer($chain['id'], true);
                if ($r && $r->new_level == NewLevel::$keys['vip3']) {
                    $commission = $amount * 0.05;
                    $this->saveCommission($r['id'], $this->order->user_id, $this->order->id, $commission, '204', '业绩奖');

                }
            }
        }

    }

    // 新团队奖 5% 2%
    private function newProfit()
    {
        $chain = Chain::getReferrerChainNew($this->order->user_id, [NewLevel::$keys['vip3']], true);

        $amount = $this->order->total_pay - $this->order->total_freight;

        if ($chain) {
            $chain = $chain[0];

            // vip4
            $vip4 = Chain::getReferrerChainNew($chain['id'], [NewLevel::$keys['vip4']], true);

            if ($vip4) {
                $vip4 = $vip4[0];

                $commission = $amount * 0.02;
                $this->saveCommission($vip4['id'], $this->order->user_id, $this->order->id, $commission, '205', '业绩奖');

                // 如果是直推
                $r = Chain::getReferrer($chain['id'], true);
                if ($r && $r->id == $vip4['id']) {
                    $commission = $amount * 0.05;
                    $this->saveCommission($vip4['id'], $this->order->user_id, $this->order->id, $commission, '206', '业绩奖');
                }
            }
        }

    }

    // 新报单, 直推与间推
    private function newRecommend()
    {
        $r1 = Chain::getReferrer($this->order->user_id, true);
        if (!$r1) {
            return;
        }

        $r2 = Chain::getReferrer($r1->id, true);

        // 设置产品价格
        $set = [
            'vip1' => 2999,
            'vip2' => 9800,
            'vip3' => 29990,
            'vip4' => 98000,
        ];

        $amount = $this->order->total_pay - $this->order->total_freight;
        $commission = 0;
        $commission2 = 0;

        if ($amount >= $set['vip4']) {

        }

        else if ($amount >= $set['vip3']) {
            if ($r1->new_level >= NewLevel::$keys['vip3']) {
                $commission = 12000;
                $this->saveCommission($r1->id, $this->order->user_id, $this->order->id, $commission, '201', '推荐奖');
            }

            if ($r2) {
                if ($r2->new_level >= NewLevel::$keys['vip3']) {
                    $commission2 = 4500;
                }
                $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $commission2, '202', '间推');
            }

            // 团队奖, 为了处理平级奖
            $this->new_team(0);
        }

        else if ($amount >= $set['vip2']) {
            if ($r1->new_level >= NewLevel::$keys['vip2']) {
                $commission = 3000;
                $this->saveCommission($r1->id, $this->order->user_id, $this->order->id, $commission, '201', '推荐奖');
            }

            if ($r2) {
                if ($r2->new_level >= NewLevel::$keys['vip2']) {
                    $commission2 = 600;
                }
                $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $commission2, '202', '间推');
            }

            // 团队奖
            $this->new_team(600);
        }

        else if ($amount >= $set['vip1']) {
            // if ($r1->new_level == NewLevel::$keys['vip4']) {
            //     $commission = 1650;
            // }
            // if ($r1->new_level == NewLevel::$keys['vip3']) {
            //     $commission = 1650;
            // }
            // if ($r1->new_level == NewLevel::$keys['vip2']) {
            //     $commission = 1200;
            // }
            // if ($r1->new_level == NewLevel::$keys['vip1']) {
            //     $commission = 1200;
            // }

            if ($r1->new_level >= NewLevel::$keys['vip1']) {
                $commission = 1500;
                $this->saveCommission($r1->id, $this->order->user_id, $this->order->id, $commission, '201', '推荐奖');
            }

            if ($r2) {
                if ($r2->new_level >= NewLevel::$keys['vip1']) {
                    $commission2 = 300;
                }
                $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $commission2, '202', '间推');
            }

            // 团队奖
            $this->new_team(300);

        }
    }

    // 新团队奖 [ 平级奖, 业绩奖 ]
    private function new_team($commission)
    {
        $amount = $this->order->total_pay - $this->order->total_freight;

        $chain = Chain::getReferrerChainNew($this->order->user_id, [NewLevel::$keys['vip3'], NewLevel::$keys['vip4']], true);
        if ($chain) {

            // 团队奖
            $t = $chain[0];
            if ($commission > 0.1) {
                $this->saveCommission($t['id'], $this->order->user_id, $this->order->id, $commission, '203', '团队奖');
            }

            // 平级奖, (相对于拿团队奖的人)
            if (isset($chain[1])) {
                $t2 = $chain[1];
                if ($t2['new_level'] >= $t['new_level']) {
                    $commission = 0.05 * $amount;
                    $this->saveCommission($t2['id'], $this->order->user_id, $this->order->id, $commission, '204', '平级奖');
                }
            }

            // 业绩奖, (相对于拿团队奖的人)
            // 这里改成了, 第1个分公司
            // $vip4 = Chain::getReferrerChainNew($t['id'], [NewLevel::$keys['vip4']], true);
            $vip4 = Chain::getReferrerChainNew($this->order->user_id, [NewLevel::$keys['vip4']], true);
            if ($vip4) {
                $vip4 = $vip4[0];
                $commission = 0.02 * $amount;
                $this->saveCommission($vip4['id'], $this->order->user_id, $this->order->id, $commission, '205', '业绩奖');
            }
        }
    }

    // 新复购差价
    protected function new_repeat_diff()
    {
        $chain = Chain::getReferrerChainNew($this->order->user_id, [
            NewLevel::$keys['vip1'],
            NewLevel::$keys['vip2'],
            NewLevel::$keys['vip3'],
            NewLevel::$keys['vip4']
        ], true);

        $award_name = '差价';
        $award_type = 211;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;
        $has_vip4 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;
        $diff_vip4 = 0;

        foreach ($chain as $user) {
            if ($user->new_level <= $this->user->new_level) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_vip3 && !$has_vip4) && $user->new_level == NewLevel::$keys['vip1']) {
                $diff_vip1 = $this->_new_diff('new1');
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3 && !$has_vip4) && $user->new_level == NewLevel::$keys['vip2']) {
                $diff_vip2 = $this->_new_diff('new2');
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_vip3 && !$has_vip4) && $user->new_level == NewLevel::$keys['vip3']) {
                $diff_vip3 = $this->_new_diff('new3');
                $diff_vip3 -= $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip3, $award_type, $award_name);
                $has_vip3 = true;
            }
            if ((!$has_vip4) && $user->new_level == NewLevel::$keys['vip4']) {
                $diff_vip4 = $this->_new_diff('new4');
                $diff_vip4 -= $diff_vip3 + $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip4, $award_type, $award_name);
                $has_vip4 = true;
            }
        }

        // 复购5% 2%
        $amount = $this->order->total_pay - $this->order->total_freight;
        $chain = Chain::getReferrerChainNew($this->order->user_id, [NewLevel::$keys['vip3'], NewLevel::$keys['vip4']], true);
        if ($chain) {
            $x = $chain[0];

            // 分公司
            if ($x->new_level == NewLevel::$keys['vip4']) {
                $commission = 0.02 * $amount;
                $this->saveCommission($x['id'], $this->order->user_id, $this->order->id, $commission, '212', '补货');
            } else {

                // 业绩部
                $commission = 0.05 * $amount;
                $this->saveCommission($x['id'], $this->order->user_id, $this->order->id, $commission, '212', '补货');

                // 再找一个分公司
                $chain = Chain::getReferrerChainNew($x['id'], [NewLevel::$keys['vip4']], true);
                if ($chain) {
                    $x = $chain[0];
                    $commission = 0.02 * $amount;
                    $this->saveCommission($x['id'], $this->order->user_id, $this->order->id, $commission, '212', '补货');
                }
            }
        }
    }

    private function _new_diff($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;

        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            // $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
            // 这里要用VIP1的价格来减
            $sum += ($product['new1'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    // 后面加上的业绩奖
    // 加盟店直推的加盟店，可以拿平级奖2%加盟店流水。
    public function add_award()
    {
        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $r = Chain::getReferrer($this->user->id, true);
        // if ($r && $r->level == UserLevel::$keys['vip2']) {
        if ($r && $r->level >= UserLevel::$keys['vip2']) {
            $r2 = Chain::getReferrer($r->id, true);

            if ($r2 && $r2->level == UserLevel::$keys['vip2']) {

                $commission = $total_amount * 0.02;

                $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $commission, '101', '业绩奖');
            }
        }
    }

    // 推荐奖
    public function recommend()
    {
        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $award_name1 = '推荐奖';
        $award_type1 = 11;
        $award_name2 = '间荐奖';
        $award_type2 = 12;

        $r = Chain::getReferrer($this->user->id, true);
        if ($r) {

            if ($total_amount >= $this->set->svip2) {
                if ($r->level >= UserLevel::$keys['svip2']) {
                    $this->saveCommission($r->id, $this->order->user_id, $this->order->id, $this->set->svip2_1, $award_type1, $award_name1);
                }
                $r2 = Chain::getReferrer($r->id, true);
                if ($r2 && $r2->level >= UserLevel::$keys['svip2']) {
                    $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $this->set->svip2_2, $award_type2, $award_name2);
                }
            }

            else if ($total_amount >= $this->set->svip1) {
                if ($r->level >= UserLevel::$keys['svip1']) {
                    $this->saveCommission($r->id, $this->order->user_id, $this->order->id, $this->set->svip1_1, $award_type1, $award_name1);
                }
                $r2 = Chain::getReferrer($r->id, true);
                if ($r2 && $r2->level >= UserLevel::$keys['svip1']) {
                    $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $this->set->svip1_2, $award_type2, $award_name2);
                }
            }

            else if ($total_amount >= $this->set->vip1) {
                $this->r21($r);
            }
        }
    }

    // 2 +1
    public function r21($r)
    {
        $award_name1 = '推荐奖';
        $award_type1 = 21;
        $award_name2 = '间荐奖';
        $award_type2 = 22;

        if ($r->level <= UserLevel::$keys['vip1']) {
            $this->saveCommission($r->id, $this->order->user_id, $this->order->id, $this->set->vip1_1, 21, $award_name1);
            $r2 = $this->getIndirect($r->id);
            if ($r2) {
                $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $this->set->vip1_2, 22, $award_name2);
            }
        } else {

            // 判断是不是第3个直推+
            $is_3 = false;
            $children = Chain::getChildrenSort($r->id, ['id']);
            // if (count($children) > $this->set->vip2) {
            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($this->order->user_id, $children);
                if (!$in) {
                    $is_3 = true;
                }
            }

            if ($is_3) {
                $this->saveCommission($r->id, $this->order->user_id, $this->order->id, $this->set->vip1_3, 41, $award_name1);
            } else {
                $this->saveCommission($r->id, $this->order->user_id, $this->order->id, $this->set->vip1_1, 31, $award_name1);
                $r2 = $this->getIndirect($r->id);
                if ($r2) {
                    $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $this->set->vip1_2, 32, $award_name2);
                }
            }
        }

    }

    // 复购差价奖
    public function diff()
    {
        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['svip1'],
            UserLevel::$keys['svip2']
        ], true);

        $award_name = '差价';
        $award_type = 3;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_svip1 = false;
        $has_svip2 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_svip1 = 0;
        $diff_svip2 = 0;

        foreach ($chain as $user) {
            if ($user->level <= $this->user->level) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_svip1 && !$has_svip2) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->_diff('vip1');
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_svip1 && !$has_svip2) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diff('vip2');
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_svip1 && !$has_svip2) && $user->level == UserLevel::$keys['svip1']) {
                $diff_svip1 = $this->_diff('svip1');
                $diff_svip1 -= $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_svip1, $award_type, $award_name);
                $has_svip1 = true;
            }
            if ((!$has_svip2) && $user->level == UserLevel::$keys['svip2']) {
                $diff_svip2 = $this->_diff('svip2');
                $diff_svip2 -= $diff_svip1 + $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_svip2, $award_type, $award_name);
                $has_svip2 = true;
            }
        }
    }

    // diff
    private function _diff($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;

        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    // 团队奖
    // 这个是普通团队奖, 已经取消, 不再使用
    public function team()
    {
        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $chain = Chain::getReferrerChain($this->order->user_id, [UserLevel::$keys['svip1'], UserLevel::$keys['svip2']], true);
        if ($chain) {
            $user = $chain[0];
            $commission = 0;
            if ($user->level == UserLevel::$keys['svip1']) {
                $commission = $this->set->team_svip1;
            }
            if ($user->level == UserLevel::$keys['svip2']) {
                $commission = $this->set->team_svip2;
            }
            $commission = $commission / 100 * $total_amount;
            $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, 2, '团队奖');
        }
    }

    // 新团队奖, 有点复杂
    // 前两条线给上级,
    // 第三条线给自己
    // 如果前两条线, 升级成 加盟店主+, 则给自己
    public function newTeam()
    {
        $r = Chain::getReferrer($this->order->user_id, true);
        if (!$r) {
            return;
        }

        // 拿奖人
        $the_referrer = Chain::getReferrer($r->id, true);
        if (!$the_referrer) {
            return;
        }

        // 1) 如果r已经升级了[发展了2+]
        // 2) r是不是the_referrer的3+
        // 3) 否则给三级

        if ($r->level >= UserLevel::$keys['vip2']) {
            return $this->_team($the_referrer);
        }

        $children = Chain::getChildrenSort($the_referrer->id, ['id']);
        // if (count($children) > $this->set->vip2) {
        if (count($children) > 2) {
            $children = [$children[0], $children[1]];
            $in = in_array($r->id, $children);
            if (!$in) {
                return $this->_team($the_referrer);
            }
        }

        $x = $this->getIndirect($the_referrer->id);
        if ($x) {
            return $this->_team($x);
        }

    }

    private function _team($user)
    {
        if ($user->level < UserLevel::$keys['svip1']) {
            return;
        }


        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $commission = 0;
        if ($user->level == UserLevel::$keys['svip1']) {
            $commission = $this->set->team_svip1;
        }
        if ($user->level == UserLevel::$keys['svip2']) {
            $commission = $this->set->team_svip2;
        }
        $commission = $commission / 100 * $total_amount;



        $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, 2, '团队奖');
    }

    // 分红奖
    public function profit()
    {
        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $svip2_list = User::find()
            ->where(['level' => UserLevel::$keys['svip2']])
            ->all();
        if ($svip2_list) {
            $commission = $this->set->profit / 100 * $total_amount / count($svip2_list);
            foreach ($svip2_list as $user) {
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, 1, '分红');
            }
        }
    }

    // 拿间推的人
    private function getIndirect($user_id)
    {
        $the_referrer = Chain::getReferrer($user_id, true);
        if (!$the_referrer) {
            return null;
        }

        // 高等级
        if ($the_referrer->level >= UserLevel::$keys['svip1']) {
            // 她的不截断
            // return $the_referrer;
        }

        // 处理两线条
        if ($the_referrer->level >= UserLevel::$keys['vip2']) {

            // 判断是否属于前2个直推
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);

            // if (count($children) > $this->set->vip2) {
            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($user_id, $children);
                if (!$in) {
                    return $the_referrer;
                } else {
                    return $this->getIndirect($the_referrer->id);
                }
            } else {
                return $this->getIndirect($the_referrer->id);
            }
        }

        return $this->getIndirect($the_referrer->id);
    }

    // 保存佣金
    protected function saveCommission($user_id, $fans_id, $order_id, $balance, $type, $name)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $fans_id;
            $model->order_id = $order_id;
            $model->balance = $balance;
            // $model->status = $status;
            $model->status = 0;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                // $account->balance += $balance;
                // 改成待返
                $account->await_balance += $balance;
                $account->save();
            }
        }
    }
}